package com.wanmait.houlang.interceptor;

import com.wanmait.houlang.service.ManagerService;
import com.wanmait.houlang.util.IgnoreToken;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private ManagerService managerService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("preHandler............");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //控制器方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //判断该方法是否添加了IgnoreToken注解
        if(method.isAnnotationPresent(IgnoreToken.class)){
            //获得控制器的方法上添加的注解
            IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);
            if(ignoreToken.required()){
                return true;
            }
        }
        //从请求头中获得token
        String token = request.getHeader("token");
        if(token==null){
            throw new Exception("没有登录");
        }

        Object o = redisTemplate.opsForValue().get(token);
        if(o==null){
            throw new Exception("未登录");
        }
        //从token中获得管理员id
//        Integer id = Integer.parseInt(JWTUtils.getAudience(token));
//        Manager manager = managerService.findById(id);
//        if(manager==null){
//            throw new Exception("没有id为"+id+"的管理员");
//        }
        //验证token是否有效
//        JWTUtils.verifyToken(token,manager.getManagerPass());
//        request.setAttribute("admin",manager);
        return true;
    }

    //执行控制器的功能处理方法之后，试图渲染之前，可以对ModelAndView处理
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


    }

    //请求调用处理完成之后，试图渲染完毕，可以对资源进行清理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
